import time
import pygame

from setting import Settings
from case import Case
from ball import Ball
import game_functions as gf
from game_status import GameStats
from button import Button
from scoreboard import Scoreboard


def run_game():
    pygame.init()
    pygame.display.set_caption("Ball Drop")

    gf.check_file()

    ai_settings = Settings()
    screen = pygame.display.set_mode((ai_settings.screen_width, ai_settings.screen_height))

    count = ai_settings.count
    max_chance = ai_settings.max_chance

    stats = GameStats(ai_settings)
    play_button = Button(ai_settings, screen, "Play", "Exit", "Replay")
    exit_button = Button(ai_settings, screen, "Play", "Exit", "Replay")
    replay_button = Button(ai_settings, screen, "Play", "Exit", "Replay")
    sb = Scoreboard(ai_settings, screen, stats, count, max_chance)
    case = Case(ai_settings, screen)
    ball = Ball(ai_settings, screen)

    while True:

        gf.check_events(case, stats, play_button, ai_settings, exit_button, replay_button)

        if stats.game_replay:
            stats.score = gf.get_stats_score()
            stats.game_replay = False
            stats.game_active = True
            stats.game_finish = False
            pygame.mouse.set_visible(False)
            count = ai_settings.count
            max_chance = ai_settings.max_chance
            sb.chance_left(count, max_chance)
            sb.prep_score()

        if stats.game_active:
            ball.rect.x = ball.x

            case.update()
            ball.update()

            if ball.rect.y >= ai_settings.screen_height:
                ball = Ball(ai_settings, screen)
                ball.blitme()
                # gf.create_ball()
                if not gf.is_catch(ball, case):
                    count += stats.count_step
                    gf.is_exit(count, max_chance, stats)
                    sb.chance_left(count, max_chance)

            if gf.is_catch(ball, case):
                stats.score += stats.score_step
                sb.prep_score()
                gf.check_high_score(stats, sb)
                time.sleep(0.5)
                ball = Ball(ai_settings, screen)
                ball.blitme()
        else:
            ball.rect.x = (ai_settings.screen_width - ball.rect.width) / 2

        gf.update_screen(ai_settings, screen, case, ball, stats, play_button, sb, exit_button, replay_button)


if __name__ == "__main__":

    run_game()
